<!DOCTYPE html>
<html>
<head>
    <title>智能规则</title>
    <style>
        .rule-form {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            max-width: 800px;
            margin: 20px auto;
        }
        .rule-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        input, select {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        button {
            padding: 8px 16px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background: #0b7dda;
        }
        #ruleList {
            grid-column: 1 / -1;
            padding-top: 20px;
        }
    </style>
</head>
<body>
    <div class="rule-form">
        <h2>条件触发规则</h2>
        <input type="text" placeholder="规则名称" id="ruleName">
        <select id="sensorType">
            <option value="temperature">温度传感器</option>
            <option value="humidity">湿度传感器</option>
            <option value="light">光照传感器</option>
            <option value="soil">土壤湿度传感器</option>
            <option value="rain">降雨量传感器</option>
            <option value="uv">紫外线指数</option>
            <option value="ph">二氧化碳浓度</option>
        </select>
        <select id="comparison">
            <option value="<">低于</option>
            <option value=">">高于</option>
        </select>
        <input type="number" id="threshold" placeholder="阈值">
        <select id="action">
            <option value="water_on">开启洒水</option>
            <option value="fan_on">开启风扇</option>
            <option value="led_on">开启LED</option>
            <option value="water_off">关闭洒水</option>
            <option value="fan_off">关闭风扇</option>
            <option value="led_off">关闭LED</option>
        </select>
        <button onclick="addRule()">添加规则</button>

        <div id="ruleList"></div>
    </div>

    <script>
        async function loadRules() {
            try {
                const res = await fetch('/api/auto_rules');
                if (!res.ok) throw new Error('获取规则失败');

                const rules = await res.json();
                document.getElementById('ruleList').innerHTML = rules
                    .map(rule => `
                        <div class="rule-item">
                            ${rule.name}: 当 ${rule.sensor === 'humidity' ? '湿度' :
                                rule.sensor === 'temperature' ? '温度' :
                                rule.sensor === 'light' ? '光照' :
                                rule.sensor === 'soil' ? '土壤湿度' :
                                rule.sensor === 'rain' ? '降雨量' :
                                rule.sensor === 'uv' ? '紫外线指数' :
                                rule.sensor === 'ph' ? '二氧化碳浓度'  : ''}
                            ${rule.operator === '>' ? '高于' : '低于'} ${rule.threshold} 时执行
                            ${rule.action === 'water_on' ? '开启洒水' :
                             rule.action === 'fan_on' ? '开启风扇' :
                             rule.action === 'led_on' ? '开启LED' :
                             rule.action === 'water_off' ? '关闭洒水' :
                             rule.action === 'fan_off' ? '关闭风扇' :
                             rule.action === 'led_off' ? '关闭LED' : ''}
                            <button onclick="deleteRule('${rule.id}')">删除</button>
                        </div>
                    `).join('');
            } catch (error) {
                console.error('加载规则失败:', error);
                document.getElementById('ruleList').innerHTML = `<div class="rule-item">加载规则失败: ${error.message}</div>`;
            }
        }

        async function addRule() {
            try {
                const rule = {
                    name: document.getElementById('ruleName').value,
                    sensor: document.getElementById('sensorType').value,
                    operator: document.getElementById('comparison').value,
                    threshold: document.getElementById('threshold').value,
                    action: document.getElementById('action').value
                };

                const res = await fetch('/api/auto_rules', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(rule)
                });

                if (!res.ok) throw new Error(await res.text());

                loadRules();
            } catch (error) {
                console.error('添加规则失败:', error);
                alert(`添加规则失败: ${error.message}`);
            }
        }

        async function deleteRule(id) {
            try {
                const res = await fetch(`/api/auto_rules?id=${id}`, { method: 'DELETE' });
                if (!res.ok) throw new Error(await res.text());
                
                loadRules();
            } catch (error) {
                console.error('删除规则失败:', error);
                alert(`删除规则失败: ${error.message}`);
            }
        }

        // 初始化加载
        loadRules();
    </script>
</body>
</html>